package com.sevenGroup.pawnshop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sevenGroup.pawnshop.Utils.CopyProperties;
import com.sevenGroup.pawnshop.controller.form.SelectStoreForm;
import com.sevenGroup.pawnshop.controller.form.StoreForm;
import com.sevenGroup.pawnshop.controller.form.pageForm;
import com.sevenGroup.pawnshop.controller.info.StoresInfo;
import com.sevenGroup.pawnshop.dao.*;
import com.sevenGroup.pawnshop.exception.sevenGroupException;
import com.sevenGroup.pawnshop.model.*;
import com.sevenGroup.pawnshop.service.StoresService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author sevenGroup
 * @since 2022-02-16
 */
@Service
public class StoresServiceImpl extends ServiceImpl<StoresDao, Stores> implements StoresService {

    @Resource
    private WarehouseStoreDao warehouseStoreDao;

    @Resource
    private StoresDao storesDao;

    @Resource
    private GoodsDao goodsDao;

    @Resource
    private UsersDao usersDao;

    @Resource
    private WarehousesDao warehousesDao;

    @Override
    public IPage<StoresInfo> selectAllStores(pageForm pageForm) throws sevenGroupException {
        if (pageForm == null) {
            throw new sevenGroupException(40001, "参数为空");
        }

        pageForm.setPageNum(pageForm.getPageNum() == null ? 1 : pageForm.getPageNum());
        pageForm.setPageSize(pageForm.getPageSize() == null ? 5 : pageForm.getPageSize());

        Page warehousesPage = new Page<>(pageForm.getPageNum(), pageForm.getPageSize());

        QueryWrapper<Stores> wrapper = new QueryWrapper<>();

        //查询指定字段
        wrapper.select("store_id", "store_name", "store_address", "store_contact", "store_tel", "store_state");
        Page page = storesDao.selectPage(warehousesPage, wrapper);
        //获取Security上下文对象
        Integer accountId = ((Account) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getAccountId();

        //根据登录的角色查询对应的门店，虽然只有一个，但是当做了集合处理
        List<Users> users = usersDao.selectList(new QueryWrapper<Users>().eq("account_id", accountId));
        //循环判断，为空则直接返回
        for (Users user : users) {
            if (user.getStoreId() == null || Integer.valueOf(user.getStoreId()) <= 0) {

                return page;
            } else {
                //新建集合，存入对象
                ArrayList<StoresInfo> storesInfos = new ArrayList<>();

                for (Object record : page.getRecords()) {
                    ArrayList<Integer> integers = new ArrayList<>();
                    Stores stores = (Stores) record;
                    StoresInfo storesInfo = CopyProperties.copyOne(stores, StoresInfo.class);
                    //循环存入userId
                    for (Users user1 : users) {
                        integers.add(Integer.valueOf(user1.getStoreId()));
                    }
                    storesInfo.setUserStoreIds(integers);

                    storesInfos.add(storesInfo);
                }
                //循环完毕后设置集合，返回
                page.setRecords(storesInfos);
            }
        }

        return page;
    }

    @Override
    public void saveStore(StoreForm storeForm) throws sevenGroupException {
        if (storeForm == null) {
            throw new sevenGroupException(40001, "参数为空");
        }
        //新增门店前，根据门店地址判断是否存在
        Stores store_address = storesDao.selectOne(new QueryWrapper<Stores>().eq("store_address", storeForm.getStoreAddress()).select("store_id", "store_name", "store_address", "store_contact", "store_tel", "store_state"));
        if (store_address != null && store_address.getStoreId() != storeForm.getStoreId()) {
            throw new sevenGroupException(40020, "该门店已存在");
        }
        //新增门店前，根据门店名称判断是否存在
        Stores store_name = storesDao.selectOne(new QueryWrapper<Stores>().eq("store_name", storeForm.getStoreName()).select("store_id", "store_name", "store_address", "store_contact", "store_tel", "store_state"));
        if (store_name != null && store_name.getStoreId() != storeForm.getStoreId()) {
            throw new sevenGroupException(40020, "该门店已存在");
        }
        //不存在则直接新增
        Stores entity = CopyProperties.copyOne(storeForm, Stores.class);
        storesDao.insert(entity);


        if (storeForm.getList() != null && storeForm.getList().size() > 0) {
            //传回的集合不为空，则添加到中间表
            for (Integer integer : storeForm.getList()) {
                WarehouseStore warehouseStore = WarehouseStore.builder().storeId(entity.getStoreId()).warehouseId(integer).build();
                warehouseStoreDao.insert(warehouseStore);
            }
        }


    }

    @Override
    public void updateStore(StoreForm storeForm) throws sevenGroupException {
        if (storeForm == null) {
            try {
                throw new sevenGroupException(40001, "参数为空");
            } catch (sevenGroupException e) {
                e.printStackTrace();
            }
        }
        //修改门店前，根据门店地址判断是否存在
        Stores store_address = storesDao.selectOne(new QueryWrapper<Stores>().eq("store_address", storeForm.getStoreAddress()).select("store_id", "store_name", "store_address", "store_contact", "store_tel", "store_state"));
        if (store_address != null && store_address.getStoreId() != storeForm.getStoreId()) {
            throw new sevenGroupException(40020, "该门店已存在");
        }
        //修改门店前，根据门店名称判断是否存在
        Stores store_name = storesDao.selectOne(new QueryWrapper<Stores>().eq("store_name", storeForm.getStoreName()).select("store_id", "store_name", "store_address", "store_contact", "store_tel", "store_state"));
        if (store_name != null && store_name.getStoreId() != storeForm.getStoreId()) {
            throw new sevenGroupException(40020, "该门店已存在");
        }

        Stores stores = CopyProperties.copyOne(storeForm, Stores.class);
        //门店表直接修改
        storesDao.updateById(stores);
        QueryWrapper<WarehouseStore> wrapper = new QueryWrapper<>();
        wrapper.eq("store_id", storeForm.getStoreId());
        //中间表要先删除在添加
        int delete = warehouseStoreDao.delete(wrapper);
        //循环取出，存入
        if (storeForm.getList() != null) {
            for (Integer integer : storeForm.getList()) {
                WarehouseStore warehouseStore = WarehouseStore.builder().warehouseId(integer).storeId(storeForm.getStoreId()).build();
                warehouseStoreDao.insert(warehouseStore);
            }
        }
        //更新用户表
        QueryWrapper<Users> usersQueryWrapper = new QueryWrapper<>();
        usersQueryWrapper.eq("store_id", storeForm.getStoreId());
        Users users = new Users();
        users.setStoreName(storeForm.getStoreName());
        usersDao.update(users, usersQueryWrapper);
        //更新商品表
        QueryWrapper<Goods> goodsQueryWrapper = new QueryWrapper<>();
        goodsQueryWrapper.eq("store_id", storeForm.getStoreId());
        Goods goods = new Goods();
        goods.setStoreName(storeForm.getStoreName());
        goodsDao.update(goods, goodsQueryWrapper);
    }

    @Override
    public IPage<StoresInfo> selectAllStoreByAll(SelectStoreForm selectStoreForm) throws sevenGroupException {

        selectStoreForm.setPageNum(selectStoreForm.getPageNum() == null ? 1 : selectStoreForm.getPageNum());
        selectStoreForm.setPageSize(selectStoreForm.getPageSize() == null ? 5 : selectStoreForm.getPageSize());
        Page warehousesPage = new Page<>(selectStoreForm.getPageNum(), selectStoreForm.getPageSize());
        QueryWrapper<Stores> wrapper = new QueryWrapper<>();

        //查询指定字段，嵌套条件进行查询
        wrapper.select("store_id", "store_name", "store_address", "store_contact", "store_tel", "store_state");
        if (selectStoreForm.getCondition() != null && selectStoreForm.getCondition() != "") {
            wrapper.and(wrapper1 -> wrapper1.like("store_name", selectStoreForm.getCondition())
                    .or()
                    .like("store_contact", selectStoreForm.getCondition())
                    .or()
                    .like("store_address", selectStoreForm.getCondition()));
        }
        if (selectStoreForm.getStoreState() != null && selectStoreForm.getStoreState() != "") {
            wrapper.eq("store_state", selectStoreForm.getStoreState());
        }
        Page page = storesDao.selectPage(warehousesPage, wrapper);
        //根据Security上下文对象获取登录的账户id
        Integer accountId = ((Account) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getAccountId();

        //获取用户集合
        List<Users> users = usersDao.selectList(new QueryWrapper<Users>().eq("account_id", accountId));

        ArrayList<StoresInfo> storesInfos = new ArrayList<>();
        //获取对应的门店对象
        for (Object record : page.getRecords()) {
            ArrayList<Integer> integers = new ArrayList<>();
            Stores stores = (Stores) record;
            StoresInfo storesInfo = CopyProperties.copyOne(stores, StoresInfo.class);

            for (Users user : users) {
                integers.add(Integer.valueOf(user.getStoreId()));
            }
            storesInfo.setUserStoreIds(integers);

            storesInfos.add(storesInfo);
        }
        page.setRecords(storesInfos);

        if (page == null) {

            throw new sevenGroupException(40007, "查询失败");

        }
        return page;
    }

    @Override
    public Stores selectStoreAndAllWarehouses(Integer storeId) throws sevenGroupException {
        if (storeId == null || storeId <= 0) {
            throw new sevenGroupException(40007, "参数异常");
        }

        //查询出门店对象
        Stores stores = storesDao.selectOne(new QueryWrapper<Stores>().eq("store_id", storeId).select("store_id", "store_name", "store_address", "store_contact", "store_tel", "store_state"));
        List<WarehouseStore> warehouseStores = warehouseStoreDao.selectList(new QueryWrapper<WarehouseStore>().eq("store_id", storeId));

        ArrayList<Integer> integers = new ArrayList<>();
        //新建集合将中间表的仓库id存入
        for (WarehouseStore warehouseStore : warehouseStores) {
            integers.add(warehouseStore.getWarehouseId());
        }
        //如果集合不等于空则进行后面的操作，为空直接返回
        if (integers == null || integers.size() <= 0) {
            return stores;
        }
        QueryWrapper<Warehouses> warehousesQueryWrapper = new QueryWrapper<>();

        List<Warehouses> warehouse_id = warehousesDao.selectList(warehousesQueryWrapper.in("warehouse_id", integers));
        //将查询出的集合进行迭代，将满足条件的元素删除
        Iterator<Warehouses> iterator = warehouse_id.iterator();

        while (iterator.hasNext()) {
            if (iterator.next().getWarehouseState().equals("关闭")) {
                iterator.remove();
            }
        }

        if (stores == null) {
            throw new sevenGroupException(40011, "查询失败");
        }

        stores.setSelectAllWarehouses(warehouse_id);

        return stores;
    }

    @Override
    public void delStore(Integer storeId) throws sevenGroupException {
        if (storeId == null || storeId <= 0) {
            throw new sevenGroupException(40001, "参数异常");
        }
        storesDao.deleteById(storeId);
        QueryWrapper<WarehouseStore> wrapper = new QueryWrapper<>();
        wrapper.eq("warehouse_id", storeId);
        warehouseStoreDao.delete(wrapper);
    }

    @Override
    public void delStoreByList(List<Integer> list) throws sevenGroupException {
        if (list == null || list.size() <= 0) {
            throw new sevenGroupException(40001, "参数为空");
        }
        storesDao.deleteBatchIds(list);
        QueryWrapper<WarehouseStore> wrapper = new QueryWrapper<>();
        wrapper.in("store_id", list);
        warehouseStoreDao.delete(wrapper);
    }
}
